package com.nk.system.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.nk.system.beans.AllBean;
import com.nk.system.beans.CriteriaBean;
import com.nk.system.beans.DropdownBean;
import com.nk.system.beans.PredictScoreBean;
import com.nk.system.beans.ProgramBean;
import com.nk.system.beans.ScoreStatBean;
import com.nk.system.service.BachelorService;
import com.nk.system.service.CalculateService;
import com.nk.system.service.PredictService;
import com.nk.system.service.ProgramService;

/**
 * Servlet implementation class AssessmentServlet
 */
public class AssessmentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	@Autowired
	private BachelorService bachelorService;
	@Autowired
	private CalculateService calculateService;
	@Autowired
	private PredictService predictService;
	@Autowired
	private ProgramService programService;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AssessmentServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		initial(request, response);
		return;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		initial(request, response);
		return;

	}
	
	private void initial(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
		
		sumScore(request, response);
		
		WebApplicationContext con = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
		bachelorService = (BachelorService)con.getBean("bachelorService");
		
		List<DropdownBean> province = bachelorService.getProvinceList("",1);
		List<DropdownBean> uniName = bachelorService.getUniversityList("", "", 1);
		List<DropdownBean> facultyName = bachelorService.getFacultyList("", "", "", 1);
		List<DropdownBean> majorName = bachelorService.getMajorList("", "", "", "", 1);
		
		request.setAttribute("provinceList", province);
		request.setAttribute("uniNameList", uniName);
		request.setAttribute("facultyList", facultyName);
		request.setAttribute("majorList", majorName);
		request.getRequestDispatcher("assessment.jsp").forward(request, response);
		return;
	}
	
	private void sumScore(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
		
		WebApplicationContext con = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
		calculateService = (CalculateService)con.getBean("calculateService");
		predictService = (PredictService)con.getBean("predictService");
		bachelorService = (BachelorService)con.getBean("bachelorService");
		programService = (ProgramService)con.getBean("programService");
		
		String zoneArr[] = request.getParameterValues("zoneName");
		String provinceArr[] = request.getParameterValues("provinceName");
		String universityArr[] = request.getParameterValues("universityName");
		String facultyArr[] = request.getParameterValues("facultyName");
		String majorArr[] = request.getParameterValues("majorName");
		
		List<String> zoneList = new ArrayList<String>();
		if(zoneArr != null) {
			for(String zone:zoneArr) {
				zoneList.add(StringEscapeUtils.unescapeJava(zone));
			}
		}
		
		List<String> provinceList = new ArrayList<String>();
		if(provinceArr != null) {
			for(String province:provinceArr) {
				provinceList.add(StringEscapeUtils.unescapeJava(province));
			}
		}
		List<String> universityList = new ArrayList<String>();
		if(universityArr != null) {
			for(String university:universityArr) {
				universityList.add(StringEscapeUtils.unescapeJava(university));
			}
		}
		List<String> facultyList = new ArrayList<String>();
		if(facultyArr != null) {
			for(String faculty:facultyArr) {
				facultyList.add(StringEscapeUtils.unescapeJava(faculty));
			}
		}
		List<String> majorList = new ArrayList<String>();
		if(majorArr != null) {
			for(String major:majorArr) {
				majorList.add(StringEscapeUtils.unescapeJava(major));
			}
		}
		
		List<PredictScoreBean> predictScoreBeanList = new ArrayList<PredictScoreBean>();
		List<ScoreStatBean> scoreStatBeanList = new ArrayList<ScoreStatBean>();
		List<CriteriaBean> criteriaBeanList = new ArrayList<CriteriaBean>();
		List<AllBean> programBeanList = new ArrayList<AllBean>();
		ProgramBean programBean = null;
		List<ProgramBean> result = bachelorService.getMajorList(zoneList, provinceList, universityList, facultyList,majorList, 1);
		
		if(zoneArr != null){
			for(ProgramBean program:result){
				
				HttpSession userSess = request.getSession();
				
				double gpax = Double.parseDouble((String) userSess.getAttribute("gpaxScore"));
				int thai = Integer.parseInt((String) userSess.getAttribute("thaiScore"));
				int social = Integer.parseInt((String) userSess.getAttribute("socialScore"));
				int eng = Integer.parseInt((String) userSess.getAttribute("engScore"));
				int math = Integer.parseInt((String) userSess.getAttribute("mathScore"));
				int science = Integer.parseInt((String) userSess.getAttribute("scienceScore"));
				int sport = Integer.parseInt((String) userSess.getAttribute("sportScore"));
				int art = Integer.parseInt((String) userSess.getAttribute("artScore"));
				int tech = Integer.parseInt((String) userSess.getAttribute("techScore"));
				int gat = Integer.parseInt((String) userSess.getAttribute("gatScore"));
				int pat1 = Integer.parseInt((String) userSess.getAttribute("pat1Score"));
				int pat2 = Integer.parseInt((String) userSess.getAttribute("pat2Score"));
				int pat3 = Integer.parseInt((String) userSess.getAttribute("pat3Score"));
				//int pat4 = Integer.parseInt((String) userSess.getAttribute("pat4Score"));
				int pat5 = Integer.parseInt((String) userSess.getAttribute("pat5Score"));
				/*int pat6 = Integer.parseInt((String) userSess.getAttribute("pat6Score"));
				int pat71 = Integer.parseInt((String) userSess.getAttribute("pat71Score"));
				int pat72 = Integer.parseInt((String) userSess.getAttribute("pat72Score"));
				int pat73 = Integer.parseInt((String) userSess.getAttribute("pat73Score"));
				int pat74 = Integer.parseInt((String) userSess.getAttribute("pat74Score"));
				int pat75 = Integer.parseInt((String) userSess.getAttribute("pat75Score"));
				int pat76 = Integer.parseInt((String) userSess.getAttribute("pat76Score"));*/
				
				int totalUserScore = 0;
			
				criteriaBeanList = calculateService.getCalcutale(program);
				
				int weigth00 = 20, weigth01 = 0, weigth02 = 0, weigth03 = 0, weigth04 = 0, weigth05 = 0, weigth06 = 0, 
						weigth71 = 0, weigth72 = 0, weigth73 = 0, weigth74 = 0, weigth75 = 0, weigth76 = 0, weigth77 = 0, 
						weigth78 = 0, weigth79 = 0, weigth80 = 0, weigth81 = 0, weigth82 = 0, weigth85 = 0;
				int minimum00 = 0, minimum01 = 0, minimum02 = 0, minimum03 = 0, minimum04 = 0, minimum05 = 0, minimum06 = 0, 
						minimum71 = 0, minimum72 = 0, minimum73 = 0, minimum74 = 0, minimum75 = 0, minimum76 = 0, minimum77 = 0,
						minimum78 = 0, minimum79 = 0, minimum80 = 0, minimum81 = 0, minimum82 = 0, minimum85 = 0;
				
				for(CriteriaBean criteria:criteriaBeanList) {
					if(criteria.getCourseID().equals("00")){
						weigth00 = criteria.getWeight();
						minimum00 = criteria.getMinimum();
					}
					if(criteria.getCourseID().equals("01")){
						weigth01 = criteria.getWeight();
						minimum01 = criteria.getMinimum();
					}
					if(criteria.getCourseID().equals("02")){
						weigth02 = criteria.getWeight();
						minimum02 = criteria.getMinimum();
					}
					if(criteria.getCourseID().equals("03")){
						weigth03 = criteria.getWeight();
						minimum03 = criteria.getMinimum();
					}
					if(criteria.getCourseID().equals("04")){
						weigth04 = criteria.getWeight();
						minimum04 = criteria.getMinimum();
					}
					if(criteria.getCourseID().equals("05")){
						weigth05 = criteria.getWeight();
						minimum05 = criteria.getMinimum();
					}
					if(criteria.getCourseID().equals("06")){
						weigth06 = criteria.getWeight();
						minimum06 = criteria.getMinimum();
					}
					if(criteria.getCourseID().equals("71")){
						weigth71 = criteria.getWeight();
						minimum71 = criteria.getMinimum();
					}
					if(criteria.getCourseID().equals("72")){
						weigth72 = criteria.getWeight();
						minimum72 = criteria.getMinimum();
					}
					if(criteria.getCourseID().equals("73")){
						weigth73 = criteria.getWeight();
						minimum73 = criteria.getMinimum();
					}
					if(criteria.getCourseID().equals("74")){
						weigth74 = criteria.getWeight();
						minimum74 = criteria.getMinimum();
					}
					if(criteria.getCourseID().equals("75")){
						weigth75 = criteria.getWeight();
						minimum75 = criteria.getMinimum();
					}
					if(criteria.getCourseID().equals("76")){
						weigth76 = criteria.getWeight();
						minimum76 = criteria.getMinimum();
					}
					if(criteria.getCourseID().equals("77")){
						weigth77 = criteria.getWeight();
						minimum77 = criteria.getMinimum();
					}
					if(criteria.getCourseID().equals("78")){
						weigth78 = criteria.getWeight();
						minimum78 = criteria.getMinimum();
					}
					if(criteria.getCourseID().equals("79")){
						weigth79 = criteria.getWeight();
						minimum79 = criteria.getMinimum();
					}
					if(criteria.getCourseID().equals("80")){
						weigth80 = criteria.getWeight();
						minimum80 = criteria.getMinimum();
					}
					if(criteria.getCourseID().equals("81")){
						weigth81 = criteria.getWeight();
						minimum81 = criteria.getMinimum();
					}
					if(criteria.getCourseID().equals("82")){
						weigth82 = criteria.getWeight();
						minimum82 = criteria.getMinimum();
					}
					if(criteria.getCourseID().equals("85")){
						weigth85 = criteria.getWeight();
						minimum85 = criteria.getMinimum();
					}
				}
				
				int sumGpax = (int)((gpax*75)*weigth00);
				int sunOnet = ((thai*3)*weigth01)+((social*3)*weigth02)+((eng*3)*weigth03)+((math*3)*weigth04)+((science*3)*weigth05)+((sport+art+tech)*weigth06);
				int sumGatPat = (gat*weigth85)+(pat1*weigth71)+(pat2*weigth72)+(pat3*weigth73)+/*(pat4*weigth74)+*/(pat5*weigth75)/*+(pat6*weigth76)+(pat71*weigth77)+
								(pat72*weigth78)+(pat73*weigth79)+(pat74*weigth80)+(pat75*weigth81)+(pat76*weigth82)*/;
				
				totalUserScore = sumGpax+sunOnet+sumGatPat;
				
				AllBean predictScore = new AllBean();
				predictScore.setScore(totalUserScore);
				
				scoreStatBeanList = predictService.getPredictResult(program);
					
				double sd1 = 0.0,mean1 = 0,sd2 = 0,mean2 = 0,sd3 = 0,mean3 = 0;
				int num1 = 0,num2 = 0,num3 = 0;
					
				for(ScoreStatBean scoreStat:scoreStatBeanList) {
					if(scoreStat.getYear().equals("2010")){
						sd1 = scoreStat.getSd();
						mean1 = scoreStat.getAvg();
						num1 = scoreStat.getPeople();
					}
					if(scoreStat.getYear().equals("2011")){
						sd2 = scoreStat.getSd();
						mean2 = scoreStat.getAvg();
						num2 = scoreStat.getPeople();
					}
					if(scoreStat.getYear().equals("2012")){
						sd3 = scoreStat.getSd();
						mean3 = scoreStat.getAvg();
						num3 = scoreStat.getPeople();
							
						predictScore.setMax(scoreStat.getMax());
						predictScore.setMin(scoreStat.getMin());
					}
				}
				
				double avgSD = ((sd1*num1)+(sd2*num2)+(sd3*num3))/(num1+num2+num3);
				double avgMean = ((mean1*num1)+(mean2*num2)+(mean3*num3))/(num1+num2+num3);
				
				double avgMean1 = avgMean+(avgSD*0.6);
				double avgMean2 = avgMean+(avgSD*1.8);
				double avgMean3 = avgMean+(avgSD*3); //avgMean1,2,3 is curve +1,+2,+3
				double avgMean4 = avgMean-(avgSD*0.6);
				double avgMean5 = avgMean-(avgSD*1.8);
				double avgMean6 = avgMean-(avgSD*3); //avgMean4,5,6 is curve -1,-2,-3
				
				if(thai>=minimum01 && social>=minimum02 && eng>=minimum03 && math>=minimum04 && science>=minimum05 && (sport+art+tech)>=(minimum06*3) && gat>=(minimum85*3) && pat1>=(minimum71*3) && pat2>=(minimum72*3) && pat3>=(minimum73*3) /*&& pat4>=(minimum74*3)*/ && pat5>=(minimum75*3)/* && pat6>=(minimum76*3)  && pat71>=(minimum77*3) && pat72>=(minimum78*3) && pat73>=(minimum79*3) && pat74>=(minimum80*3) && pat75>=(minimum81*3) && pat76>=(minimum82*3)*/){
					if(totalUserScore >= avgMean3){
						predictScore.setStar("6");
					}
					else if(totalUserScore >= avgMean2){
						predictScore.setStar("5");
					}
					else if(totalUserScore >= avgMean1){
						predictScore.setStar("4");
					}
					else if(totalUserScore >= avgMean4){
						predictScore.setStar("3");
					}
					else if(totalUserScore >= avgMean5){
						predictScore.setStar("2");
					}
					else if(totalUserScore >= avgMean6){
						predictScore.setStar("1");
					}
					else{
						predictScore.setStar("0");
					}
				}
				else{
					predictScore.setStar("8");
				}
				programBean = programService.getProgram(program);
				
				predictScore.setId(programBean.getId());
				predictScore.setZone(programBean.getZone());
				predictScore.setCountry(programBean.getCountry());
				predictScore.setUname(programBean.getUname());
				predictScore.setFaculty(programBean.getFaculty());
				predictScore.setMajor(programBean.getMajor());
				
				programBeanList.add(predictScore);
			}
		}
		request.setAttribute("predictScoreBeanList", predictScoreBeanList);
		request.setAttribute("programBeanList", programBeanList);
	}
	
}
